package com.example.sunmiv1.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.LossGoodsInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;

import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ReportLossSearchAdapter extends RecyclerView.Adapter<ReportLossSearchAdapter.ViewHolder> {

    private List<LossGoodsInfo.DataBean> list;
    private CheckBoxListener mCheckBoxListener;

    private Context context;
    private ACache aCache;

    private static final String TAG = "InventorySearchAdapter";

    public ReportLossSearchAdapter(Context context, List<LossGoodsInfo.DataBean> list) {
        this.context = context;
        this.list = list;
        aCache = ACache.get(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.inventory_search_adapter, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        Resources resources = context.getResources();
        viewHolder.inventorySearchAdapterName.setText(resources.getString(R.string.inventory_name) +
                list.get(position).getGoods_name());
        viewHolder.inventorySearchAdapterSku.setVisibility(View.VISIBLE);
        if ("2".equals(list.get(position).getAttribute_state())) {
            viewHolder.inventorySearchAdapterSku.setText(resources.getString(R.string.inventory_sku) +
                    list.get(position).getSku_name());
            viewHolder.inventorySearchAdapterFreightNumber.setText(resources.getString(R.string.inventory_freightNumber) +
                    list.get(position).getSku_goods_number());
            viewHolder.inventorySearchAdapterBarcode.setText(resources.getString(R.string.inventory_barcode) +
                    list.get(position).getSku_code());
        } else {
            viewHolder.inventorySearchAdapterSku.setVisibility(View.GONE);
            viewHolder.inventorySearchAdapterFreightNumber.setText(resources.getString(R.string.inventory_freightNumber) +
                    list.get(position).getGoods_number());
            viewHolder.inventorySearchAdapterBarcode.setText(resources.getString(R.string.inventory_barcode) +
                    list.get(position).getGoods_code());
        }
        if ("2".equals(aCache.getAsString("userType")) && "1".equals(aCache.getAsString("showPrice"))) {
            viewHolder.inventorySearchAdapterPrice.setVisibility(View.VISIBLE);
            viewHolder.inventorySearchAdapterPrice.setText(resources.getString(R.string.inventory_costPrice) +
                    list.get(position).getCost_price());
        }
        if ("1".equals(aCache.getAsString("userType"))) {
            viewHolder.inventorySearchAdapterPrice.setVisibility(View.VISIBLE);
            viewHolder.inventorySearchAdapterPrice.setText(resources.getString(R.string.inventory_costPrice) +
                    list.get(position).getCost_price());
        }
        if ("1".equals(aCache.getAsString("is_check_show_invenum"))) {
            viewHolder.inventorySearchAdapterStock.setVisibility(View.VISIBLE);
        } else {
            viewHolder.inventorySearchAdapterStock.setVisibility(View.GONE);
        }
        viewHolder.inventorySearchAdapterStock.setText(resources.getString(R.string.inventory_stock) +
                list.get(position).getGoods_num());
        viewHolder.inventorySearchAdapterCheck.setOnCheckedChangeListener(null);
        viewHolder.inventorySearchAdapterCheck.setChecked(list.get(position).isChecked());
        final int index = position;
        viewHolder.inventorySearchAdapterCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            list.get(index).setChecked(isChecked);
            notifyDataSetChanged();
        });
        if (TextUtils.isEmpty(list.get(position).getCompany())) {
            viewHolder.inventorySearchAdapterUnit.setVisibility(View.GONE);
        } else {
            viewHolder.inventorySearchAdapterUnit.setText(resources.getString(R.string.purRefundDetail_company) +
                    ":" + list.get(position).getCompany());
            viewHolder.inventorySearchAdapterUnit.setVisibility(View.VISIBLE);
        }
        viewHolder.inventorySearchAdapterInventoryName.setText(R.string.reportLossNUm);
        viewHolder.inventorySearchAdapterInventory.setText(list.get(position).getLoss_num());

        if ("1".equals(list.get(position).getSerial_number_state())) {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            viewHolder.inventorySearchAdapterInventory.setVisibility(View.GONE);
            Log.e(TAG, "onBindViewHolder: 商品的庫存========" + list.get(position).getLoss_num());
            if (TextUtils.isEmpty(list.get(position).getLoss_num())) {
                viewHolder.inventorySearchAdapterInventoryTv.setText("0");
            } else {
                viewHolder.inventorySearchAdapterInventoryTv.setText(list.get(position).getLoss_num());
            }
        } else {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            viewHolder.inventorySearchAdapterInventory.setVisibility(View.VISIBLE);
        }

        if ("2".equals(list.get(position).getAttribute_state())) {
            viewHolder.inventorySearchAdapterInventory.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
        } else {
            if ("1".equals(list.get(position).getPricing_method())) {
                viewHolder.inventorySearchAdapterInventory.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
            } else {
                viewHolder.inventorySearchAdapterInventory.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
            }
        }
        final TextWatcher dgnTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                limitDecimal(charSequence, viewHolder.inventorySearchAdapterInventory);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.inventorySearchAdapterInventory.hasFocus()) {
                    list.get(index).setLoss_num(viewHolder.inventorySearchAdapterInventory.getText().toString().trim());
                }

            }
        };
        setETFocusChangeListener(position, dgnTextWatcher, viewHolder.inventorySearchAdapterInventory);
        viewHolder.inventorySearchAdapterRemarkLin.setVisibility(View.VISIBLE);
        viewHolder.inventorySearchAdapterRemark.setText(list.get(position).getRemark());
        final EditText remark = viewHolder.inventorySearchAdapterRemark;
        remark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                list.get(index).setRemark(remark.getText().toString().trim());
            }
        });
        viewHolder.llPurchaseOrderChoose.setVisibility(View.GONE);
        viewHolder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(position);
            }
        });
    }
    private ReportLossListAdapter.Choose choose;
    public void setChoose(ReportLossListAdapter.Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index);
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.inventorySearch_adapter_check)
        CheckBox inventorySearchAdapterCheck;
        @BindView(R.id.inventorySearch_adapter_name)
        TextView inventorySearchAdapterName;
        @BindView(R.id.inventorySearch_adapter_sku)
        TextView inventorySearchAdapterSku;
        @BindView(R.id.inventorySearch_adapter_freightNumber)
        TextView inventorySearchAdapterFreightNumber;
        @BindView(R.id.inventorySearch_adapter_barcode)
        TextView inventorySearchAdapterBarcode;
        @BindView(R.id.inventorySearch_adapter_price)
        TextView inventorySearchAdapterPrice;
        @BindView(R.id.inventorySearch_adapter_stock)
        TextView inventorySearchAdapterStock;
        @BindView(R.id.inventorySearch_adapter_inventoryName)
        TextView inventorySearchAdapterInventoryName;
        @BindView(R.id.inventorySearch_adapter_inventory)
        EditText inventorySearchAdapterInventory;
        @BindView(R.id.inventorySearch_adapter_remarkLin)
        LinearLayout inventorySearchAdapterRemarkLin;
        @BindView(R.id.inventorySearch_adapter_remark)
        EditText inventorySearchAdapterRemark;
        @BindView(R.id.ll_purchase_order_choose)
        LinearLayout llPurchaseOrderChoose;
        @BindView(R.id.inventorySearch_adapter_unit)
        TextView inventorySearchAdapterUnit;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;


        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    // 全選
    public void checkAll() {
        Iterator<LossGoodsInfo.DataBean> iterable = list.iterator();
        while (iterable.hasNext()) {
            iterable.next().setChecked(true);
        }
        notifyDataSetChanged();
    }

    // 全不選
    public void checkAllNot() {
        Iterator<LossGoodsInfo.DataBean> iterable = list.iterator();
        while (iterable.hasNext()) {
            iterable.next().setChecked(false);
        }
        notifyDataSetChanged();
    }

    // 移除一個
    public void removeOne(int position) {
        list.remove(position);
    }

    /* 移除多個 */
    public void removeMore(SparseArray<Integer> positions) {
//        list.r
    }


    public static interface CheckBoxListener {
        void setCheckBoxListener(boolean isChecked, int position);
    }

    public void setCBListener(CheckBoxListener cbListener) {
        this.mCheckBoxListener = cbListener;
    }

    /**
     * 限制小數點後三位
     *
     * @param charSequence str
     * @param et           et
     */
    private void limitDecimal(CharSequence charSequence, EditText et) {
        LogUtil.i("onTextChanged: charSequence=" + charSequence.toString());
        if (charSequence.toString().contains(".")) {
            if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                et.setText(charSequence.toString().
                        substring(0, charSequence.toString().length() - 1));
                et.setSelection(charSequence.length() - 1);
            } else {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                    charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                    et.setText(charSequence);
                    et.setSelection(charSequence.length());
                }
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            et.setText(charSequence);
            et.setSelection(2);
        }

        if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                et.setText(charSequence.subSequence(1, 2));
                et.setSelection(1);
            }
        }
    }

    /**
     * 設置edittext焦點的監聽器
     *
     * @param position    pos
     * @param textWatcher watcher
     * @param editText    et
     */
    private void setETFocusChangeListener(int position, TextWatcher textWatcher, EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                ((EditText) v).addTextChangedListener(textWatcher);
                Log.e("addTextChanged", position + "");
            } else {
                ((EditText) v).removeTextChangedListener(textWatcher);
                Log.e("removeTextChanged", position + "");
            }
        });
    }

}
